<template>
  <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
    <div class="order-from">
      <div class="from-head">
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
          <el-button @click="cancel" size="medium">取 消</el-button>
        </div>
        <div class="order">
          <span>订单编号：{{from.orderCoding}}</span>
        </div>
      </div>
      <div class="from-body">

        <div class="body-head">
          <div class="item head-ma">
            <span>供应商：</span>
            <el-select v-model="from.suppliersId"  filterable placeholder="请选择供应商">
              <el-option
                v-for="item in suppliersList"
                :key="item.id"
                :label="item.suppliersName"
                :value="item.id">
              </el-option>
            </el-select>
          </div>

          <div class="item head-ma">
            <span>单据日期：</span>
            <el-date-picker
              v-model="from.buyTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </div>

          <div class="item head-ma">
            <span>交货日期：</span>
            <el-date-picker
              v-model="from.deliveryTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </div>

          <div class="item head-ma">
            <span>采购项目：</span>
            <el-select v-model="from.itemId"  filterable placeholder="请选择">
              <el-option
                v-for="item in itemList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="item head-ma item1" style="width: 186px;">
            <span>类型：</span>
            <el-radio-group v-model="from.type">
                <el-radio :label="0">购货</el-radio>
                <el-radio :label="1">退货</el-radio>
            </el-radio-group>
          </div>

          <div class="item head-ma item1">
            <span>采购人：</span>
              <el-input v-model="from.orderUser"    maxlength="60" prefix-icon="el-icon-search"></el-input>
          </div>

          <div class="item head-ma item1">
            <span>制单人：</span>
              <el-input v-model="from.createBy" maxlength="60"   prefix-icon="el-icon-search" ></el-input>
          </div>

        </div>


        <div class="body-table">
          <el-table  :data="orderList" border :row-class-name="tableRowClassName" >

            <el-table-column label="序号" align="center" type="index" />


            <el-table-column label="编码/商品名称" align="center"   width="180" prop="categorieId"  >
              <template slot-scope="scope">
                <el-select v-model="scope.row.categorieId"  filterable @change="categorieChange(scope.row.index)" >
                  <el-option
                    v-for="item in InfoList"
                    :key="item.id"
                    :label="item.id+'/'+item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="规格" align="center"  width="180" prop="specification" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.specification" maxlength="100" ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="单位" align="center"  width="180" prop="unit" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.unit"  maxlength="1" ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="仓库" align="center"  width="180" prop="warehouseId" >
              <template slot-scope="scope">
                <el-select v-model="scope.row.warehouseId"  filterable >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="数量" align="center" prop="number" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.number" maxlength="10" @change="isMoney(scope.row.index,0)" ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="单价" align="center" prop="price" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" maxlength="20"  @change="isMoney(scope.row.index,1)" ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="总金额" align="center" prop="total" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.total" maxlength="20"  @change="isMoney(scope.row.index,2)" ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="折扣率(%)" align="center" prop="discountRate" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.discountRate" maxlength="2"  @change="isMoney(scope.row.index,3)"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="折扣金额" align="center" prop="discountPrice" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.discountPrice" maxlength="10"   :disabled="true" @change="isMoney(scope.row.index,4)"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="商品类别" align="center"  width="180" prop="goodsType" >
              <template slot-scope="scope">
                <el-select v-model="scope.row.goodsType"  filterable >
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="备注" align="center"  width="200" prop="remark" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" maxlength="200" ></el-input>
              </template>
            </el-table-column>


          </el-table>
        </div>

        <div class="add-line"><div @click="init(1)">+</div></div>

        <div class="body-bott">
          <div class="bott-head">
            <span >合计:</span>
            <span>{{from.totalNum}}</span>
            <span >总金额:</span>
            <span >{{from.totalPrice}}</span>
            <span>优惠率(%)：</span>
            <span>
              <el-input v-model="from.PreferentialRate"  @change="isMoney(0,5)"></el-input>
            </span>
            <span>优惠金额：</span>
            <span>
              <el-input v-model="from.PreferentialPrice" @change="isMoney(0,6)"></el-input>
            </span>

            <span >优惠后金额:</span>
            <span>{{from.PreferentialLastPrice}}</span>
          </div>
          <div class="remark">
            <el-input
              type="textarea"
              maxlength="200"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 10}"
              placeholder="请输入内容"
              v-model="from.remark">
            </el-input>
          </div>

        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import {suppliersList} from '@/api/jxc/suppliers' //供应商
  import { warehouseQueryList } from '@/api/jxc/warehouse'//仓库
  import { procurementItemQueryList } from '@/api/jxc/procurementItem' //项目名称
  import { listProduct } from "@/api/jxc/productInfo";  //商品信息
  import { listCategory} from "@/api/jxc/productCategory"; //商品分类
  import {getorderInfo,addorder,editorder,ProcurementOrderDetailsList} from '@/api/jxc/order'
export default {
  name: 'addfrom', // 文件导入
  props:["type","orderId"],
  data() {
    return {
      title:"新增采购订单",
      open: false,
      from:{PreferentialLastPrice:0,type:0,totalNum:0,totalPrice:0},
      //供应商列表
      suppliersList: [],
      //采购项目列表
      itemList:[],
      //商品名称
      InfoList:[],
      //商品分类
      categoryList:[],
      //仓库
      warehouseList:[],

      //表单
      orderList:[],
      queryParams: {
        pageNum: 1,
        pageSize: 99999,
      },
    }
  },
  watch: {
    type: function(newValue, oldValue) {
      if(newValue >0){
        this.open = true;
        this.orderList=[]
        if(newValue==1) {
          this.title= "新增采购订单"
          this.init(0)
        }
        if(newValue==2){
          this.getorderInfoById()
          this.title= "修改采购订单"
        }
      }
    },

  },
  created(){
      this.infoFromDateList()
  },

  methods: {

    categorieChange(index){
        var categorieId = this.orderList[index].categorieId
        this.InfoList.forEach(res=>{
          if(res.id === categorieId){
            this.orderList[index].goodsType = res.belongCategory
            this.orderList[index].specification  =res.specification
            this.orderList[index].unit= res.unit
            this.orderList[index].price  = res.price
          }
        })
        this.orderList[index].warehouseId  = this.warehouseList[0].id
        this.orderList[index].number  = 1

        if(this.orderList[index].price){
          this.calculateTotalPrice(index,0);
        }else{
          this.orderList[index].total  = 0.00
        }

    },
    getorderInfoById(){
      var id = undefined
      if(this.orderId instanceof Array){
        id = this.orderId[0]
      }else{
        id = this.orderId
      }
      getorderInfo( {id:id}).then(res=>{
        this.from = res.data
        this.$emit("change")
        ProcurementOrderDetailsList({id:res.data.id}).then(r=>{
          this.orderList = r.data
          for (var i = 0;i<this.orderList.length;i++){
           this. categorieChange(i)
          }
        })
      })
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },


    /** 提交按钮 */
    submitForm: function() {
      if(this.from.suppliersId==undefined){
        return this.msgWarning("请选择供应商")
      }
      if(this. from.buyTime ==undefined){
        return this.msgWarning("请选择供单据日期")
      }
      if(this.from.deliveryTime ==undefined){
        return this.msgWarning("请选择交货日期")
      }
      if(this.from.type ==undefined){
        return this.msgWarning("请选择采购类型")
      }
      var num = 0;
      var list = []
      for(var i = 0 ;i <this.orderList.length;i++){
          if(this.orderList[i].status==true ){
            console.log(this.orderList[i])
            if(this.orderList[i].categorieId ==undefined||this.orderList[i].categorieId<1){
              return  this.msgWarning("第"+(i+1)+"请选择商品名称！")
            }

            if(this.orderList[i].specification==undefined||this.orderList[i].specification.length < 0){
              return  this.msgWarning("第"+(i+1)+"请输入商品规格！")
            }
            if(this.orderList[i].unit==undefined||this.orderList[i].unit.length < 0){
              return  this.msgWarning("第"+(i+1)+"请输入商品单位！")
            }

            if(this.orderList[i].warehouseId==undefined||this.orderList[i].warehouseId < 1){
              return  this.msgWarning("第"+(i+1)+"请选择仓库")
            }

           if(this.orderList[i].number==undefined||this.orderList[i].number<=0){
            return  this.msgWarning("第"+(i+1)+"行的数量必须大于0！")
           }

           if(this.orderList[i].price==undefined||this.orderList[i].price <= 0){
             return  this.msgWarning("第"+(i+1)+"行的单价必须大于0！")
           }

           if(this.orderList[i].total==undefined||this.orderList[i].total<=0){
             return  this.msgWarning("第"+(i+1)+"行的总金额必须大于0！")
           }
             list.push(this.orderList[i])
             num++
          }
      }
      if(num<=0){
        return  this.msgWarning("请购买商品，在提交订单")
      }
      this. from.buyTime = this.parseTime(this. from.buyTime,'{y}-{m}-{d}').toString()
      this.from.deliveryTime = this.parseTime(this.from.deliveryTime,'{y}-{m}-{d}').toString()
      this.from .orderDate = this.parseTime(this. from.buyTime,'{y}{m}{d}').toString()
      this.from .orderList  = JSON.stringify(list)
      if (this.from.id != undefined) {
        editorder(this.from).then(response => {
          if (response.code === 0) {
            this.msgSuccess("修改成功");
            this.open = false;
          } else {
            this.msgError("修改失败");
          }
          this.$emit("change")
        });
      } else {
        addorder(this.from).then(response => {
          if (response.code === 0) {
            this.open = false;
            this.getList();
            this.msgSuccess("添加成功")
          } else {
            this.msgError("添加失败")
          }
          this.$emit("change")
        });

      }

    },

    isMoney(index,type) {
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      if (type == 0) {
        const num= /^[0-9]*$/
       if(!num.test( this.orderList[index].number)){
         this.msgError("第"+(index+1)+"行的  数量  请输入数字！！")
         this.orderList[index].number = undefined
         this.orderList[index].status =false
        }else{
         this.calculateTotalPrice(index,0);
       }
      }else if(type==1){
        if(!reg.test( this.orderList[index].price)){
          this.msgError("第"+(index+1)+"行的  单价  请输入数字！！")
          this.orderList[index].price = undefined
          this.orderList[index].status =false
        }else{
          this.calculateTotalPrice(index,0);
        }

      }else if(type==2){

        if(!reg.test( this.orderList[index].total)){
          this.msgError("第"+(index+1)+"行的  总金额  请输入数字！！")
          this.orderList[index].total = undefined
          this.orderList[index].status =false
        }else{
           var total =   this.orderList[index].price*this.orderList[index].number
            if(total != this.orderList[index].total ){
              this.msgError("第"+(index+1)+"行的 总价格不匹配！！")
              this.calculateTotalPrice(index,0)
            }
        }

      }else if(type==3){
        if(!reg.test( this.orderList[index].discountRate)){
          this.msgWarning("第"+(index+1)+"行的  折扣率请输入数字！！")
          this.orderList[index].discountRate = undefined
          this.orderList[index].discountPrice = undefined
          this.calculateTotalPrice(index,0);
        }else{
          if(this.orderList[index].discountRate){
           this.calculateTotalPrice(index,0);
          }
        }
      }else if(type==4){
        if(!reg.test( this.orderList[index].discountPrice)){
          this.msgWarning("第"+(index+1)+"行的  折扣金额  金额请输入数字！！")
          this.orderList[index].discountPrice = undefined
        }
      }else if(type==5){
        if(!reg.test( this.from.PreferentialRate)){
          this.msgWarning("优惠率 请输入数字！！")
          this.from.PreferentialRate = undefined
        }else{
          this.calculateTotalPrice(undefined,1);
        }
      }else if(type==6){
        if(!reg.test( this.from.PreferentialPrice)){
          this.msgWarning("优惠金额  请输入数字！！")
          this.from.PreferentialPrice = undefined
        }else{
          this.calculateTotalPrice(undefined,1);
        }
      }
    },

    //计算总金额
    calculateTotalPrice(index,type){
      if(type==0){
        if(this.orderList[index].price>0&&this.orderList[index].number>0){
          var total =   this.orderList[index].price*this.orderList[index].number;
          if(this.orderList[index].discountRate!=undefined&&this.orderList[index].discountRate!=null&&this.orderList[index].discountRate!=''&&this.orderList[index].discountRate<100){
            const rate =  this.orderList[index].discountRate /100
            const price = (100 -  this.orderList[index].discountRate) / 100;
            this.orderList[index].total = total * rate
            this.orderList[index].discountPrice = total * price
            this.orderList[index].status =true
          }else{
            this.orderList[index].total = total
            this.orderList[index].status =true
          }
        }else{
          this.msgError("第"+(index+1)+"行的  单价 和数量不能为空！！")
          this.orderList[index].status =false
        }

        var money = 0 ;
        var totalNum = 0;
        this.orderList.forEach(res=>{
          if( res.status){
            totalNum = parseInt(totalNum) + parseInt(res.number)
            let totalprice = parseFloat(money) + parseFloat(res.total)
            money = totalprice.toFixed(2)
          }
        })
        this.from.totalNum = totalNum
        this.from.totalPrice = money

      }else if(type == 1 ){
        if(this.from.totalPrice>0){
          if(this.from.PreferentialRate&&this.from.PreferentialPrice){
            this.msgWarning("优惠率 和优惠金额只能输入一个！！")
            this.from.PreferentialRate =undefined
            this.from.PreferentialPrice =undefined
            this.from.PreferentialLastPrice = 0
          }else {
            if(this.from.PreferentialRate>0&&this.from.PreferentialPrice==undefined){
              var m =(this.from.PreferentialRate/100) *  this.from.totalPrice
              this.from.PreferentialLastPrice = m.toFixed(2)
            }else if(this.from.PreferentialRate ==undefined&&this.from.PreferentialPrice>0){
              this.from.PreferentialLastPrice  =  parseFloat(this.from.totalPrice) -parseFloat(this.from.PreferentialPrice)
            }
          }
        }else{
          this.msgWarning("请选择购买的商品！！")
        }
      }
    },
// 表单重置
    reset() {
      this. from = {PreferentialLastPrice:0,type:0,totalNum:0,totalPrice:0}
      this.orderList = []
      this.init(0)
    },
    //获取当前点击行下标
    tableRowClassName ({row, rowIndex}) {
      //把每一行的索引放进row
      row.index = rowIndex;
    },

    infoFromDateList(){
      //项目
      procurementItemQueryList(this.queryParams).then(res => {
        this.itemList = res.data
      })
      //供应商
      suppliersList(this.queryParams).then(res=>{
        this.suppliersList=res.data
      })
      //仓库
      warehouseQueryList(this.queryParams).then(res => {
        this.warehouseList = res.data
      })
      //商品信息
      listProduct(this.queryParams).then(response => {
        this.InfoList = response.data
      });
      //商品分类
      listCategory().then(res=>{
        this.categoryList = res.data
      })

    },
    init(type){

      if(type==0){
        for (var i = 0 ; i< 5;i++){

          var map = {
            status:false,
            categorieId:undefined, //商品信息
            warehouseId:undefined, //仓库id
            number:undefined, //数量
            specification:undefined, //规格
            unit:undefined,  //单位
            price:undefined, //单价
            total:undefined, //总金额
            discountRate:undefined, //折扣率
            discountPrice:undefined, //折扣金额
            goodsType:undefined, //商品类型
            remark:undefined //备注
          }
          this.orderList.push(map)
        }
      }else{
        var map = {
          status:false,
          categorieId:undefined, //商品信息
          warehouseId:undefined, //仓库id
          number:undefined, //数量
          specification:undefined, //规格
          unit:undefined,  //单位
          price:undefined, //单价
          total:undefined, //总金额
          discountRate:undefined, //折扣率
          discountPrice:undefined, //折扣金额
          goodsType:undefined, //商品类型
          remark:undefined //备注
        }
        this.orderList.push(map)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.order-from{
  width: 100%;
  min-height: 500px;
  height: 100%;
  .from-head{
    height: 52px;
    padding-bottom: 15px ;
    background-color: #FFFFFF;
    position: relative;
    border-bottom: 2px solid #cecece;
    .dialog-footer{
      display: inline-block;
      width: 30%;
    }
    .order{
      display: inline-block;
      position: absolute;
      font-size: 18px;
      right: 0;
      top: 17px;
      min-width: 269px;
    }
  }
  .from-body{
    margin-top: 15px;
    background-color: #FFFFFF;
    min-height: 450px;
    position: relative;
    .body-head{
      position: relative;
      .item{
        display: inline-block;
        width: 320px;
        .el-select{
          width: 222px;
        }
      }
      .item1{
        margin-top: 15px;
        .el-input{
          width: 236px;
        }
      }
      .head-ma{
        margin-right: 15px;
        font-size: 18px;
        font-weight: 600;
        color: #717171;
      }
    }
    .body-table{
      margin-top: 15px;
    }
    .add-line{
      position: relative;
      div{
        margin: 0 auto;
        font-size: 53px;
        text-align: center;
        line-height: 36px;
        padding: 0 20px;
        width: 100px;
        color: #b3b3b3;
        cursor: pointer;
      }
      div:hover{
        color: #409EFF;
      }
    }
    .body-bott{
      margin-top: 15px;
      margin-bottom: 50px;
      position: relative;
      .bott-head{
        position: relative;
        border: 1px solid #cecece;
        span{
          display: inline-block;
          border-right: 1px solid #cecece;
          font-size: 18px;
          padding: 10px
        }
        span:nth-child(2), span:nth-child(4),span:nth-child(10){
          color: #8bb5f0;
          width: 200px;
          text-align: left;
        }
        span:nth-child(10){
          border: 0;
        }
        span:nth-child(6),span:nth-child(8){
          padding: 0;
        }
        span:nth-child(1),span:nth-child(3),span:nth-child(5),span:nth-child(7),span:nth-child(9){
          border: 0;
          text-align: center;
        }

      }
    }
    .remark{
      margin-top: 15px;
      position: relative;
    }
  }
}
</style>
